<template>
  <div class="taskType">
    <!-- 上传 -->
    <div
      v-if="cOperType(guidelineObj.operType, [operType['upload']])"
      class="content"
      @click="handelShowRegion(guidelineObj.operType)"
    >
      <div class="content" :class="{ 'is-showMoreContent': answerRegion || StateIsUnSelect_UserIsTeacherOrDesginer}">
        <!-- <div class="iconUploadBox">
          <img src="../../../../../assets/images/answer.png" />
        </div>
        <div class="iconUploadBoxhover">
          <img src="../../../../../assets/images/answerHover.png" />
        </div> -->
        <guidelineType :type="guidelineObj.operType" />
        <div
          class="title"
          v-html="guidelineObj.description"
          @click="handelCLickGuidelines"
        />
        <div class="donwIconBox">
          <img
            src="../../../../../assets/images/down3.png"
            class="downIcon"
            :class="{'downIcon-acitve': answerRegion}"
            v-if="
              cTaskState === taskState['studying'] ||
              (cTaskState === taskState['studied'] && !unShowGroupIcon)
            "
            @click.stop="handelShowRegion(guidelineObj.operType)"
          />
        </div>
        <div
          class="mustInput"
          v-if="guidelineObj.description == '' && submissionCourseInfoStatus"
          title="引导文内容必填"
        >
          *
        </div>
        <div
          class="mustInput"
          v-if="guidelineObj.foreignID == '' && submissionCourseInfoStatus"
          title="题组不能为空（类型：题组）"
        >
          *
        </div>
      </div>
    </div>
    <!-- 简答 -->
    <div
      v-if="
        cOperType(guidelineObj.operType, [
          operType['show'],
          operType['reply'],
          operType['refer'],
          operType['brush'],
          operType['game'],
          operType['archive'],
        ])
      "
      class="content"
      @click="handelShowRegion(guidelineObj.operType)"
    >
      <div class="content" :class="{ 'is-showMoreContent': answerRegion || StateIsUnSelect_UserIsTeacherOrDesginer}">
        <!-- <div class="iconUploadBox">
          <img src="../../../../../assets/images/answer.png" />
        </div>
        <div class="iconUploadBoxhover">
          <img src="../../../../../assets/images/answerHover.png" />
        </div> -->
        <guidelineType :type="guidelineObj.operType" />
        <div
          class="title"
          v-html="guidelineObj.description"
          @click="handelCLickGuidelines"
        ></div>
        <div class="donwIconBox">
          <img
            src="../../../../../assets/images/down3.png"
            class="downIcon"
            :class="{'downIcon-acitve': answerRegion}"
            v-if="
              (cTaskState === taskState['studying'] || cTaskState === taskState['studied']) &&
              !unShowGroupIcon
            "
            @click.stop="handelShowRegion(guidelineObj.operType)"
          />
        </div>
        <div
          class="mustInput"
          v-if="guidelineObj.description == '' && submissionCourseInfoStatus"
          title="引导文内容必填"
        >
          *
        </div>
      </div>
    </div>
    <!-- 上传、简答的回答面板 -->
    <div
      class="answerRegion"
      :class="{
        'answerRegion-active': answerRegion,
        isBQuestion: cOperType(guidelineObj.operType, [
          operType['brush']
        ]),
      }"
      v-if="isChoose && !onlyShowGuideline"
    >
    <!-- v-if="isChoose" 修复切换页面后富文本组件报错 -->
      <div
        :class="{
          isChecked:
            ((guideScore && guideScore !== -8) || guideRemark !== '') &&
            !unShowGroupIcon && 
            cTaskState == taskState['studied'],
          isBrush: cTaskState == taskState['studied'],
        }"
        style="flex: 1; position: relative; max-width: 100%"
      >
        <!-- 文件上传 -->
        <div
          v-if="cOperType(guidelineObj.operType, [operType['upload']]) && !isTimeOut"
          class="upload"
        >
          <upload
            ref="uploadComponents"
            :courseID="courseID"
            :chooseNo="chooseNo"
            :thisIndex="thisIndex"
            :item="item"
            :titem="titem"
            :studyData="guidelineObj.studyData"
            :uploadData="uploadData"
            :unShowGroupIcon="unShowGroupIcon"
            @uploadDataChange="handleUploadDataCallback"
            :titemState="titem.state"
            :currNo="currNo"
            :accept="guidelineObj.accept"
            :acceptText="guidelineObj.accept"
            :limit="guidelineObj.limit"
            :isTimeOut="isTimeOut"
          />
        </div>
        <!-- 归档 -->
        <div
          v-if="cOperType(guidelineObj.operType, [operType['archive']]) && !isTimeOut"
          class="upload"
        >
          <upload
            ref="uploadComponents"
            :courseID="courseID"
            :chooseNo="chooseNo"
            :thisIndex="thisIndex"
            :item="item"
            :titem="titem"
            :studyData="guidelineObj.studyData"
            :uploadData="uploadData"
            :unShowGroupIcon="unShowGroupIcon"
            @uploadDataChange="handleUploadDataCallback"
            :titemState="titem.state"
            :currNo="currNo"
            :isTimeOut="isTimeOut"
            :isArchive="true"
            :multiple="false"
            :accept="guidelineObj.accept || '.doc,.docx'"
            :acceptText="guidelineObj.accept || '.doc,.docx'"
            :limit="guidelineObj.limit"
            :selectedTutorName="selectedTutorName"
          />
        </div>
        <!-- <div
          v-if="cOperType(guidelineObj.operType, [operType['upload']])"
          class="upload"
        >
          <el-button type="text" @click="fileLInkShow = true">上传链接</el-button>
          <filelink @uploadDataChange="uploadDataChange" @handelcloseFileLink="handelcloseFileLink" :fileLInkShow="fileLInkShow" :uploadData="uploadData" />
        </div> -->
        <div
          v-if="cOperType(guidelineObj.operType, [operType['brush']])"
          class="textareaBox"
        >
          <brushQuestions
            :iframeShow="iframeShow"
            :item="item"
            :iframeRouter="iframeRouter"
            :foreignID="guidelineObj.foreignID"
            @handleUpdateSessionID="handleUpdateSessionID"
            @handleUpdateTaskScore="handleUpdateTaskScore"
            @handleIframeClose="handleIframeClose"
            :creativeCourse="creativeCourse"
            :studyCourse="true"
            :currNo="currNo"
            :isTimeOut="isTimeOut"
          />
          <el-button type="text" size="mini" @click.stop="iframeShow = true" v-if="cTaskState !== taskState['studied']">进入刷题</el-button>
        </div>
        <div
          v-if="cOperType(guidelineObj.operType, [operType['game']])"
          class="textareaBox"
        >
          <p>敬请期待</p>
        </div>
        <div
          v-if="cOperType(guidelineObj.operType, [operType['refer']])"
          class="textareaBox"
        >
          <p>查阅类型引导文不需要上交内容</p>
        </div>
        <div
          v-if="cOperType(guidelineObj.operType, [operType['reply']])"
          class="textareaBox"
        >
          <!-- <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入内容"
            v-model="submitContentStr"
            @input="textChange"
            @keydown.native="handelKeyDown(false)"
            @blur="handelBlur(true)"
            :disabled="cTaskState == taskState['studied'] || unShowGroupIcon"
            class="textareaInput"
          ></el-input> -->
          <wangEidtor v-if="answerRegion" :editId="new Date().getTime()" :placeholder="'请输入内容'" :menus="['link']" :value="submitContentStr" :isInit="isInit" :disabled="cTaskState == taskState['studied'] || unShowGroupIcon || isTimeOut" @change="handelKeyDown(true,$event)" />
        </div>
        <div class="textareaBox" v-if="cOperType(guidelineObj.operType, [operType['show']])">
          <div>
            <setLink style="margin-bottom: 10px" @change="handleChangeLink" :value="submitContentStr" :titemState="titem.state" :isTimeOut="isTimeOut" />
            <upload
              ref="uploadComponents"
              :courseID="courseID"
              :chooseNo="chooseNo"
              :currNo="currNo"
              :thisIndex="thisIndex"
              :item="item"
              :titem="titem"
              :studyData="guidelineObj.studyData"
              :uploadData="uploadData"
              :unShowGroupIcon="unShowGroupIcon"
              @uploadDataChange="handleUploadDataCallback(...arguments, true)"
              :titemState="titem.state"
              :multiple="false"
              :isSetLink="true"
              :accept="guidelineObj.accept || '.zip,.rar'"
              :acceptText="guidelineObj.accept || '.zip,.rar'"
              :limit="guidelineObj.limit"
              :isTimeOut="isTimeOut"
            />
          </div>
        </div>
      </div>
      <div
        v-if="
          ((guideScore && guideScore !== -8) || guideRemark !== '') &&
          !unShowGroupIcon && 
          cTaskState == taskState['studied'] &&
          
          guidelineObj.operType !== operType['brush'] &&
          commentTime > lastUpdatedTime
        "
        class="teacherRemarkAndScore"
        :class="{ isBrushComment: cTaskState == taskState['studied'] }"
      >
        <div class="remarkBox">
          <div class="title">评分</div>
          <div class="content">{{ guideScore }}</div>
        </div>
        <div class="scoreBox">
          <div class="title">评语</div>
          <div class="content">{{ guideRemark }}</div>
        </div>
      </div>
    </div>
    <previewImgVidoeFile
      :showPerview="showPerview"
      @close="handelclose"
      :showData="showData"
    />
  </div>
</template>

<script>
import { operType, taskState } from "@/util/guidingtextType";
import {
  debounce,
  location,
  location_QuestionBank,
  changeSubmitContentfomart,
  isJSONstr,
} from "@/util/tool";
const upload = () => import("@/views/courses/detail/task_N/taskType_N/compoment/studyUpload.vue");
const previewImgVidoeFile = () =>
  import("@/components/previewImgVidoeFile/previewImgVidoeFile");
// const brushQuestions = () =>
//   import("@/views/courses/detail/task_N/taskType_N/compoment/brushQuestions");
const brushQuestions = () =>
  import("@/components/questionBankIframeDialog/index");
const wangEidtor = () => import("@/components/wangEditor/index.vue")
const setLink = () => import("@/views/courses/detail/task_N/taskType_N/compoment/setLink")
import { getChooseUpdateTaskResult } from "@/request/courses";
import { mapState } from "vuex";
import { loadAllVideo } from "@/util/loadVideo";
import guidelineType from "@/components/guidelineTypeIcon/index";
import { getNewTaskStudyData, getNewGuidelineStudyData } from "@/util/mockTaskData.js"
import { TeacherAllNum, TeacherOfTheCourse, UserOfTheCourseDesigner } from "@/util/teacherAuth.js";
import { Session } from "@/util/storage/session"
import { download } from "@/util/download"
// import filelink from "@/views/courses/detail/task_N/taskType_N/compoment/fileLink"
export default {
  components: {
    // upload: resolve => {require(['@/components/upload'], resolve)}, //懒加载
    // previewImgVidoeFile: resolve => {require(['@/components/previewImgVidoeFile/previewImgVidoeFile'], resolve)}, //懒加载
    upload,
    previewImgVidoeFile,
    brushQuestions,
    guidelineType,
    wangEidtor,
    setLink
    // filelink
  },
  data() {
    return {
      operType,
      taskState,
      showVideo: false,
      answerRegion: false,
      submitContentStr: "",
      uploadData: {}, // 上传文件后的返回的数据 {"data": {}, "isEncoded": false}
      // currentIndexData: {},
      guideScore: null, // 评分
      guideRemark: null, // 评价
      lastUpdatedTime: null,
      commentTime: null,
      canuseUpdateBtn: false, // 已有提交数据
      // taskGroupID: null, // 当前任务组ID
      // guidelineID: null, // 当前引导文ID
      isSubmit: true, // 判断当前引导文是否提交
      isSaveLocal: true, // 判断当前引导文是否已保存到本地
      showPerview: false, // 显示引导文的图片、视频、文档
      showData: {}, // 需要预览的数据
      iframeShow: false, // 刷题弹窗
      iframeRouter: "", // 刷题链接
      fileLInkShow: false,
      isInit: true,
      isTimeOut: false // 超时
    };
  },
  props: {
    thisIndex: Number, // 当前引导文索引
    courseID: Number, // 课程ID
    currNo: Number,
    cTaskState: String, // 任务的状态
    chooseNo: Number, // 学生选修ID
    guidelineObj: Object, // 当前引导文课程默认数据
    item: Object, // 当前任务组的数据
    titem: Object, // 当前引导文所属任务的数据
    taskID: Number, // 任务组所在课程的编号-任务所在任务组的编号-引导文所在任务的编号
    userId: Number, // 用户id
    taskGroupID: Number, // 任务组ID
    unShowGroupIcon: Boolean, // 在教师查看课程详情页面属于控制类参数
    submissionCourseInfoStatus: Boolean, // 提交创作系统数据的状态
    myStudyData: Array,
    creativeCourse: Boolean,
    isChoose: Boolean, // 是否已选课
    tutorStaffUserID: Number, // 开设课程的教师
    tutorIDToClassIDMap: String, // 其它任课教师
    mainDesignerUserID: Number, // 课程主设计师
    otherDesigerUserIDList: String, // 课程其它设计师
    nTaskSettings: Object,
    onlyShowGuideline: Boolean, // 点击时可显示引导文
    selectedTutorName: String, // 指导教师名字
  },
  watch: {
    // 监听学习数据 数据发生变化时修改为新的数据
    guidelineObj(newValue) {
      this.getScoreComment();
    },
    // this.getScoreComment();
    // answerRegion(n, o) {
    //   this.getScoreComment();
    // },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    getTaskState() {
      return this.guidelineObj.state;
    },
    /**
     * @description 判断类型
     */
    cOperType: () => {
      return function (type, condition) {
        if (condition.indexOf(type) !== -1) return true;
        return false;
      }
    },
    getUserAuth() {
      return this.userInfo.authNum
    },
    // 用户是否是教师身份
    checkUserIsTeacher() {
      return TeacherAllNum.find(item => this.getUserAuth?.some(sitem => sitem == item))
    },
    // 用户是否属于该课程的任课教师或其它任课教师
    getTeacherOfTheCourse () {
      return TeacherOfTheCourse({tutorStaffUserID: this.tutorStaffUserID, tutorIDToClassIDMap: this.tutorIDToClassIDMap}, this.userInfo)
    },
    // 用户是否属于该课程的设计师
    getUserOfTheCourseDesigner() {
      return UserOfTheCourseDesigner({mainDesignerUserID: this.mainDesignerUserID,otherDesigerUserIDList: this.otherDesigerUserIDList}, this.userInfo)
    },
    // 还未选择课程,用户身份权限可查看更多内容
    StateIsUnSelect_UserIsTeacherOrDesginer() {
      return (!this.answerRegion && ((this.checkUserIsTeacher && this.getTeacherOfTheCourse) || this.getUserOfTheCourseDesigner))
    }
  },
  created() {
    // this.taskGroupID = Number(this.gitem.taskGroupID); // 任务组ID
    // this.taskID = Number(this.titem.taskID); // 任务ID
    if (this.guidelineObj.operType === "刷题") {
      this.iframeRouter = `${location_QuestionBank(window)}/brush/${
        this.guidelineObj.foreignID ? this.guidelineObj.foreignID : "0"
      }`;
      // 本地测试地址
      // this.iframeRouter = `http://localhost:3000/qb/brush/${
      //   this.guidelineObj.foreignID ? 1 || this.guidelineObj.foreignID : "0"
      // }`;
    }
    this.$nextTick(() => {
      this.loadAllVideo();
    });
  },
  methods: {
    // 打开折叠组件
    handelShowRegion(gType) {
      // 判断是否有学习数据
      if ((!(this.cTaskState == taskState['unstudy']) || this.onlyShowGuideline) && !this.unShowGroupIcon) {
        this.answerRegion = !this.answerRegion;
        if (gType == operType['brush'] && this.cTaskState !== taskState['studied']) this.iframeShow = this.answerRegion
      }
    },
    // textarea的值发生改变
    textChange() {
      this.isSubmit = false;
      this.isSaveLocal = false;
    },
    // 简答框键盘按下 防抖函数控制数据保存
    handelKeyDown: debounce(
      function (immediate,data) {
        if (this.guidelineObj.studyData) {
          this.uploadData = this.guidelineObj.studyData.submitContent;
        }
        if (this.cTaskState == "已学") return;
        this.submitContentStr = data.data
        this.saveToLocalStroage();
      },
      200,
      false
    ),
    // 简答引导文输入框失去焦点
    handelBlur: debounce(
      function () {
        if (this.guidelineObj.studyData) {
          this.uploadData = this.guidelineObj.studyData.submitContent;
        }
        // debugger
        if (this.cTaskState == "已学") return;
        this.saveToLocalStroage();
      },
      200,
      true
    ),
    // 打开文件 上传
    openFile() {
      this.$refs.uploadComponents.openFile();
    },
    // 已上传的文件数据
    handelUploadedData(data) {
      this.uploadData = data;
    },
    // 上传文件数据返回
    async handleUploadDataCallback(data, noRequestSaveStudyData, isSetLink) {
      this.uploadData = data;
      this.isSubmit = false;
      this.isSaveLocal = false;
      if (isSetLink) {
        // const subFiles = data.data?.filePaths?.[0]?.subFiles
        // if(subFiles?.length) {
          // const getFileUrl = this.getHtmlFile(this.sortFileType(subFiles))
        Session.remove(`/api/queryresult/listbycurrNo?currNo=${this.currNo}`)
        this.$store.dispatch("stuShow/fetchStuShowListByUserID", {userID: this.userInfo.userID})
        // 自动解压文件后设置链接
        const filePaths = data.data?.filePaths?.[0]?.subFiles
        let url = ''
        if (filePaths) {
          // 判断是否为默认dist打包格式。index.html在dist的下一级
          if (filePaths?.length === 1 && filePaths[0].isDir) {
            if (filePaths[0]?.fileUrl) {
              url = this.getHtmlFile(this.sortFileType(filePaths))
              // filePaths[0]?.fileUrl + '/index.html'
            }
          } else if (filePaths?.length !== 1) {
            // 解压后已经自带了父级路径及文件名
            url = this.getHtmlFile(this.sortFileType(filePaths))
          } else {
            this.$antdMessage.error('非规范打包目录，请自行设置链接。')
          }
          this.handleChangeLink(url)
        } else {
          this.handleChangeLink(url)
        }
        // } else {
        //   this.$antdMessage.error({content: "压缩文件为空,请检查文件"})
        // }
      }
      if (this.cTaskState == "已学") return;
      const saveToStroage = await this.saveToLocalStroage();
      if (noRequestSaveStudyData) return
      saveToStroage && this.$emit("handleUploadFile",{
        taskIndex: this.taskGroupID + '-' + this.taskID,
        taskGroupID: this.taskGroupID,
        taskID: this.taskID,
        name: this.titem.name,
      })
    },
    // 递归获取html文件
    getHtmlFile(subFiles) {
      let url = ""
      for (let i = 0; i < subFiles?.length; i++) {
        if (url) return url;
        if (subFiles[i].isDir) {
          subFiles[i].subFiles = this.sortFileType(subFiles[i].subFiles)
          return this.getHtmlFile(subFiles[i].subFiles)
        } else {
          if (subFiles[i]?.type == 'html' || /\.html$/.test(subFiles[i]?.fileUrl)) {
            url = subFiles[i].fileUrl
            return url;
          }
          if (/\.html$/.test(subFiles[i]?.fileName)) {
            url = subFiles[i].fileUrl
            return url;
          }
        }
      }
      return url;
    },
    // 给文件夹排序
    sortFileType(data) {
      return data.sort(function(a,b){
      if(!a.isDir && b.isDir) // 如果 文件a不是目录，b是目录 位置不变
        return -1;
      else //否则，位置互换
        return 1;
      });
    },
    // 设置链接
    handleChangeLink(data) {
      this.submitContentStr = data
      if (this.uploadData?.data?.showLink !== undefined) {
        this.uploadData.data.showLink = data
      } else {
        if (!this.uploadData.data) this.uploadData.data = {
          baseFileUrl: "", filePaths: [], showLink: ""
        }
        this.uploadData.data.showLink = ""
      }
      this.saveToLocalStroage();
    },
    // 数据保存在localStorage
    saveToLocalStroage(isSaveSessionID, session_id, isSaveScore, score) {
      return new Promise((resolve,reject) => {
        if (!this.isChoose) return resolve(false)
        let currNo = Number(this.currNo);
        // 修复保存时已经离开学习页面，无法获取currNo
        if (!currNo) return resolve(false);

        // 判断studyData是否存在 且是否有内容
        let localData = localStorage.getItem("studyData");
        localData = localData ? JSON.parse(localData) : {};
        if (!localData[currNo]) localData[currNo] = {}
        const newMystudyData = JSON.parse(JSON.stringify(localData[currNo]?.[this.userInfo.userID]))
        let mystudydata = localData[currNo]?.[this.userInfo.userID];

        if (!mystudydata) {
          mystudydata = [];
        }

        //mystudydata找到taskid对应的元素，如能找到，则更新该数据， 若找不到，则加入新数据
        // debugger
        const oldTaskResult = mystudydata.find(
          (item) => item.taskID == this.titem.taskID
        );

        const gid = this.guidelineObj.guidelineID;
        if (oldTaskResult) {
          if (!oldTaskResult.guidelineResults[gid]) {
            oldTaskResult.guidelineResults[gid] = getNewGuidelineStudyData(
              this.guidelineObj
            );
          }
          oldTaskResult.notSaved = true;
          oldTaskResult.taskGroupID = this.taskGroupID;
          oldTaskResult.guidelineResults[gid].lastUpdatedTime =
            new Date().getTime();
          oldTaskResult.guidelineResults[gid].submitContent =
            this.getInputSubmitContent(oldTaskResult.guidelineResults[gid].submitContent.data);
          console.log(oldTaskResult.guidelineResults[gid]);
        } else {
          const newTaskResult = getNewTaskStudyData(this.taskGroupID, this.titem, this.chooseNo, currNo);
          newTaskResult.guidelineResults[gid].lastUpdatedTime =
            new Date().getTime();
          newTaskResult.guidelineResults[gid].submitContent =
            this.getInputSubmitContent();
          mystudydata.push(newTaskResult);
        }

        // 将题库的session_id保存
        if (isSaveSessionID) {
          let newStuData = mystudydata.find(
            (item) => item.taskID == this.titem.taskID
          );
          if (session_id) newStuData.guidelineResults[gid].session_id = session_id;
          if (!newStuData.guidelineResults[gid].submitContent.data)
            // 判断是否有旧的数据，有的话赋值给data
            newStuData.guidelineResults[gid].submitContent = {
              data: newStuData.guidelineResults[gid]?.submitContent?.data || [],
              isEncoded: false,
            };
          let data = newStuData.guidelineResults[gid].submitContent.data;
          // 将之前保存的session_id转换为数组保存
          if (!Array.isArray(data)) {
            data = []
            if (typeof val==='number'&&String(data)!='NaN') {
              data = [Number(data)];
            }
          }
          // 将当前session_id存入数组
          if (data.indexOf(session_id) === -1) data.push(session_id);
          // newStuData.guidelineResults[gid].submitContent.data = session_id;
          if(!this.isInit) this.$emit("handleChangeSubmitContent", this.titem.taskID);
        }

        // 将题库分数保存在任务的score
        if (isSaveScore) {
          let newStuData = mystudydata.find(
            (item) => item.taskID == this.titem.taskID
          );
          newStuData.taskScore = Number(score);
          newStuData.calScore = Number(score);
          newStuData.guidelineResults[gid].gameOrExciseScore = Number(score);
          newStuData.guidelineResults[gid].guidelineScore = Number(score);
          newStuData.guidelineResults[gid].guidelineComment = "已提交";
          if(!this.isInit) this.$emit("handleChangeSubmitContent", this.titem.taskID);
        }

        if (this.guidelineObj.foreignID) {
          let newStuData = mystudydata.find(
            (item) => item.taskID == this.titem.taskID
          );
          delete newStuData.guidelineResults[gid].foreignID
          delete newStuData.guidelineResults[gid].foreign_title
        }

        localData[currNo][this.userInfo.userID] = mystudydata;
        localStorage.setItem("studyData", JSON.stringify(localData));

        // 引导文答案已保存到本地
        this.isSaveLocal = true;
        if(!this.isInit) this.$emit("handleChangeSubmitContent", this.titem.taskID);
        this.isInit = false
        resolve(true)
      })
    },
    // 删除文件类型
    removeFileType(data, baseFileUrl) {
      if (data.type) delete data.type;
      let exp = new RegExp(baseFileUrl + "/", "g");
      let httpExp = new RegExp(location(window), "g");
      let arr = [];
      data.fileUrl = data.fileUrl.replace(httpExp, "").replace(exp, "");
      // debugger;
      if (data.subFiles && data.subFiles.length) {
        data.subFiles?.forEach((item) => {
          // debugger;
          if (item.type) delete item.type;
          if (item.subFiles) {
            arr.push(this.removeFileType(item, item.fileUrl));
          } else {
            arr.push(item);
          }
          item.fileUrl = item.fileUrl
            .replace(httpExp, "")
            .replace(baseFileUrl + "/", "");
        });
      } else {
        return data;
      }
    },

    // 点击引导文 todo test
    handelCLickGuidelines(e) {
      // todo change to switch Function
      if (e.target.tagName === "VIDEO") {
        window.event ? (window.event.cancelBubble = true) : e.stopPropagation();
        this.formatObjdata(e.target.attributes[":src"].value);
        e.preventDefault();
        // this.showPerview = true
      } else if (e.target.tagName === "IMG") {
        window.event ? (window.event.cancelBubble = true) : e.stopPropagation();
        this.formatObjdata(e.target.currentSrc);
        e.preventDefault();
        // this.showPerview = true
      } else if (e.target.tagName === "A") {
        window.event ? (window.event.cancelBubble = true) : e.stopPropagation();
        let url = e.target.href;
        // 使用正则将http开头的链接转换为https，并且是以http://codelover.club或http://www.codelover.club开头的链接。
        url = url.replace(/http:\/\/(www\.)?codelover\.club/g, "https://$1codelover.club");
        // e.target.download = e.target.innerText;
        // download(url, e.target.innerText)
        window.open(url)
        e.preventDefault();
        // this.formatObjdata(e.target.href);
        // this.showPerview = true
      }
    },
    // 关闭预览引导文文件窗口
    handelclose() {
      this.showPerview = false;
    },
    handelcloseFileLink() {
      this.fileLInkShow = false
    },
    // 格式化对象数据
    formatObjdata(url) {
      let obj = {
        type: "",
        url: "",
      };
      obj.type = url.substring(url.lastIndexOf(".") + 1);
      // 如果当前链接是bilibili网站则播放时打开bilibili播放器
      if (url.indexOf("bilibili.com") !== -1) {
        // obj.type = 'bilibiliPlay'
        window.open(url);
        return;
      }
      obj.fileUrl = url;
      if (obj.type && obj.fileUrl) {
        this.showPerview = true;
        this.showData = obj;
      }
    },
    // 绑定分数 评价 答案
    getScoreComment() {
      if (
        this.guidelineObj === undefined ||
        this.guidelineObj.operType == operType['brush']
      )
        return;
      // debugger;
      this.guideScore = this.guidelineObj.studyData?.guidelineScore;
      this.guideRemark = this.guidelineObj.studyData?.guidelineComment;
      this.lastUpdatedTime = this.guidelineObj.studyData?.lastUpdatedTime;
      this.commentTime = this.guidelineObj.studyData?.commentTime;
      this.canuseUpdateBtn =
        this.guidelineObj.studyData?.submitContent != false ? true : false;
      // 将提交的答案 赋值给textarea双向绑定的属性 上传 展示 简答
      if (
        this.cOperType(this.guidelineObj.operType, [
          // operType['show'],
          operType['reply'],
          operType['game'],
          // "上传",
        ])
      ) {
        this.submitContentStr =
          this.guidelineObj?.studyData?.submitContent.data;
        // 引导文submitContent.data类型强制转换
        if (typeof this.submitContentStr === "object") {
          this.$set(this.guidelineObj.studyData.submitContent, "data", "");
          this.submitContentStr = "";
        }
      }
      if (
        (this.cOperType(this.guidelineObj.operType, [operType['upload']] || 
        this.cOperType(this.guidelineObj.operType, [operType['archive']])) ||
          this.cOperType(this.guidelineObj.operType, [operType['show']])) &&
        this.guidelineObj.studyData
      ) {
        if (typeof this.guidelineObj.studyData?.submitContent === "string") {
          this.guidelineObj.studyData.submitContent = {
            data: {
              baseFileUrl: "",
              filePaths: [],
            },
            isEncoded: false,
          };
          if (this.cOperType(this.guidelineObj.operType, [operType['show']])) {
            if (!this.guidelineObj.studyData.submitContent?.data?.showLink) this.guidelineObj.studyData.submitContent.data.showLink = ""
          }
        }
        if (!this.guidelineObj.studyData?.submitContent?.data) {
          this.$set(this.guidelineObj.studyData, "submitContent", {});
          this.$set(this.guidelineObj.studyData.submitContent, "data", {
            baseFileUrl: "",
            filePaths: [],
          });
        }
        this.uploadData = this.guidelineObj.studyData?.submitContent;
        if (typeof this.uploadData === "string" || !this.uploadData?.data) {
          let dataObj = {
            baseFileUrl: "",
            filePaths: [],
          }
          this.$set(this.guidelineObj.studyData.submitContent, "data", dataObj);
          this.uploadData = dataObj;
        }
        if (this.cOperType(this.guidelineObj.operType, [operType['show']])) {
          if (!this.guidelineObj.studyData.submitContent.data.showLink) this.$set(this.guidelineObj.studyData.submitContent.data, "showLink", "");
          this.uploadData = this.guidelineObj.studyData.submitContent
        }
        this.guidelineObj.studyData.submitContent = {data: this.guidelineObj.studyData?.submitContent?.data || {}}
        if (this.guidelineObj.studyData?.submitContent?.data && !this.guidelineObj.studyData.submitContent.data?.showLink) {
          this.guidelineObj.studyData.submitContent.data.showLink = ""
        }
        this.submitContentStr = this.guidelineObj.studyData?.submitContent?.data?.showLink || "";
      }
      this.$nextTick(() => {
        this.loadAllVideo();
      });
    },
    // 关闭iframe
    handleIframeClose() {
      this.iframeShow = false;
    },
    // 加载所有视频
    loadAllVideo() {
      return loadAllVideo(this);
    },
    // 获取当前引导文输入的内容
    getInputSubmitContent(submitContentData) {
      if (this.guidelineObj.operType === operType['upload'] || this.guidelineObj.operType === operType['archive'] || this.guidelineObj.operType === operType['show']) {
        if (!Object.keys(this.uploadData).length) {
          this.uploadData = {
            baseFileUrl: "",
            filePaths: [],
          }
          if (this.cOperType(this.guidelineObj.operType, [operType['show']])) {
            this.uploadData.data.showLink = this.submitContentStr || ""
          }
        }
        return this.uploadData;
      } else {
        const data = { data: this.submitContentStr, isEncoded: false };
        // 判断是不是刷题的引导文，将原数据保存。
        if (this.guidelineObj.operType === operType['brush']) data.data = submitContentData
        return data
      }
    },
    // 题库传回的session_id
    async handleUpdateSessionID(session_id, dom, params) {
      const saveToStroage = await this.saveToLocalStroage(true, session_id);
      saveToStroage && this.$emit(
        "handleUpdateSessionID",
        {
          taskGroupID: this.taskGroupID,
          taskID: this.taskID,
          name: this.titem.name,
          guidelineID: this.guidelineObj.guidelineID,
        },
        dom,
        params,
        session_id
      );
    },
    async handleUpdateTaskScore(score, dom, params, session_id) {
      const taskIsOnlyGuideline = this.guidelineObj.foreign_type == "刷题" ? false : this.titem.guidelines.length == 1
      const saveToStroage = await this.saveToLocalStroage(true, session_id, true, score);
      saveToStroage && this.$emit(
        "handleUpdateTaskScore",
        {
          taskGroupID: this.taskGroupID,
          taskID: this.taskID,
          name: this.titem.name,
          guidelineID: this.guidelineObj.guidelineID,
        },
        dom,
        params,
        session_id,
        taskIsOnlyGuideline,
        this.item,
        this.titem
      );
    },
    // 检测任务限时状态
    handleCheckTaskTimeState(titem) {
      return new Promise((resolve) => {
        // 如果没有限时数据则通过检测
        if (
          (!this.nTaskSettings && !this.courseInfo?.taskSettings) ||
          !this.nTaskSettings?.[titem.taskID]
        ) {
          return resolve(true);
        } else {
          let timeSetting =
            this.nTaskSettings[titem.taskID] ||
            this.courseInfo.taskSettings[titem.taskID];
          let currTime = new Date().getTime();
          // if (timeSetting.beginTime && timeSetting.cutOffTime) {
          // 任务还未到开始学习时间
          if (
            timeSetting.beginTime &&
            this.toMs(timeSetting.beginTime) > currTime &&
            timeSetting.state == "生效"
          ) {
            if (titem.state == taskState['unstudy']) {
              // this.$antdMessage.warning({
              //   content: "未到开始学习时间！",
              // });
              return resolve(false);
            }
          }
          // 任务已经超出学习时间
          if (
            timeSetting.cutOffTime &&
            this.toMs(timeSetting.cutOffTime) < currTime &&
            timeSetting.state == "生效"
          ) {
            // 超出时间时 开始学习、重新学习弹出提示。完成学习不作限制
            if (
              titem.state == taskState['unstudy'] ||
              titem.state == taskState['studied'] ||
              titem.state == taskState['studying']
            ) {
              // this.$antdMessage.warning({
              //   content: "已超出任务限定学习时间！",
              // });
              return resolve(false);
            }
          }
          resolve(true);
        }
      });
    },
    toMs(data) {
      return !data ? 0 : new Date(data).getTime();
    },
  },
  async mounted() {
    this.getScoreComment();
    const timeout = await this.handleCheckTaskTimeState(this.titem)
    if (!timeout) this.isTimeOut = true
  },
};
</script>

<style lang="stylus">
.taskType {
  height: auto;

  .content {
    cursor: pointer;
    display: flex;
    // align-items: center;
    align-items: flex-start;
    min-height: 47px;
    font-family: PMingLiU-ExtB;
    font-size: 14px;
    color: #000000;

    .iconUploadBox, .iconUploadBoxhover {
      margin-right: 10px;
      width: 24px;
      height: 27px;

      img {
        object-fit: cover;
      }
    }

    .iconUploadBoxhover {
      display: none;
    }

    .iconPlayBox {
      margin-right: 10px;
      width: 24px;
      height: 24px;

      img {
        object-fit: cover;
      }
    }

    .iconBriefanswerBox {
      margin-right: 10px;
      width: 24px;
      height: 27px;

      img {
        object-fit: cover;
      }
    }

    .title {
      padding-top: 3px;
      // flex: 0;
      // width: 543px;
      // width: 70%;
      flex: 1;
      font-family: PMingLiU-ExtB;
      font-size: 14px;
      color: #000000;
      word-spacing: 5px;

      p {
        display: none;
        font-family: fangsong;
        font-size: 16px;
        font-weight: bold;

        a {
          padding-right: 25px;
          position: relative;
          background-color: transparent !important;
        }

        a::after {
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          width: 20px;
          height: 20px;
          background-image: url('~@/assets/images/linkIcon.svg');
          background-size: 20px auto;
          background-repeat: no-repeat;
          transform: translate(0, -4px);
        }
      }

      p:first-child {
        display: block;
      }
    }

    .is-showMoreContent {
      .title {
        p {
          display: block;
        }
      }

      .downIcon {
        transform: rotate(180deg);
      }

      .downIcon-acitve {
        transform: rotate(360deg);
      }
    }

    .finishTask {
      margin: 0 19px 0 auto;
      display: flex;
      align-items: center;
      font-family: PMingLiU-ExtB;
      font-size: 12px;
      color: #666666;

      .tips {
        font-family: PMingLiU-ExtB;
        font-size: 12px;
        color: #666666;
      }

      .iconBox {
        margin-left: 5px;
        line-height: 1;

        img {
          vertical-align: initial;
          width: 14px;
          height: 14px;
        }
      }
    }

    .content {
      flex: 1;
      padding-top: 10px;
      padding-bottom: 5px;

      .downIcon {
        width: 25px;
        margin: 0;
        object-fit: cover;
        height: 100%;
        transition: all 0.2s linear;
      }

      .donwIconBox {
        width: 25px;
        min-height: 25px;
      }

      .startBrush {
        margin-right: 5px;
        cursor: pointer;
        outline: none;
        width: 72px;
        height: 29px;
        border-radius: 5px;
        border: none;
        font-family: Yu Gothic UI;
        font-size: 14px;
        color: #ffffff;
        background: #f6ad35;
      }

      video, img {
        max-width: 100%;
      }
    }
  }

  .content:hover {
    background-color: #fff6e1;
    border-radius: 8px;

    .iconUploadBox {
      display: none;
    }

    .iconUploadBoxhover {
      display: block;
    }

    .guidelineTypeIcon {
      display: none;
    }

    .guidelineTypeIcon-hover {
      display: block;
    }
  }

  .answerRegion {
    display: flex;
    align-items: flex-start;
    // padding-top: 5px;
    padding-left: 39px;
    height: 0;
    transition: all 0.4s linear;
    overflow: hidden;

    .textareaBox {
      margin-top: 7px;

      .el-textarea {
        .el-textarea__inner {
          resize: none;
          max-height: 130px !important;
          border-radius: 5px;
          border: solid 1px #707070;
        }

        .el-textarea__inner::-webkit-scrollbar {
          width: 4px;
          height: 1px;
        }

        /* 定义滚动条的滑块的样式有圆角和阴影以及自定义的背景色 */
        .el-textarea__inner::-webkit-scrollbar-thumb {
          border-radius: 4px;
          -webkit-box-shadow: inset 0 0 1px #bfc4c3;
          background: #dbdbdb;
        }

        /* 定义滚动条所在轨道的样式。有圆角和阴影以及淡色系的背景色 */
        .el-textarea__inner::-webkit-scrollbar-track {
          -webkit-box-shadow: inset 0 0 1px #E6FAF3;
          border-radius: 4px;
        }
      }
    }

    .btn {
      margin-top: 13px;
      display: flex;

      button {
        cursor: pointer;
        outline: none;
        margin-right: 59px;
        width: 80px;
        height: 26px;
        background-color: #f6ad35;
        border-radius: 5px;
        border: none;
        font-family: PMingLiU-ExtB;
        font-size: 14px;
        color: #ededed;
      }

      .unUpdate {
        cursor: not-allowed;
        background-color: #bfbfbf;
      }

      .updateBtn {
        margin: 0;
        cursor: not-allowed;
        background-color: #bfbfbf;
      }

      .canuseUpdate {
        cursor: pointer;
        background-color: #f6ad35;
      }
    }

    .upload {
      margin-top: 7px;
      line-height: 1;
    }

    .isChecked {
      margin-top: 5px;
      flex: unset !important;
      width: 355px;
    }

    .isBrush {
      flex: 1 !important;
      width: 100%;
    }

    .teacherRemarkAndScore {
      margin-top: 5px;
      flex: 1;
      // min-height: 130px;
      padding: 26px 0 22px 49px;
      display: flex;
      flex-flow: column;
      justify-content: space-between;

      .remarkBox, .scoreBox {
        display: flex;
        min-height: 30px;
        border: 1px solid #BFBFBF;
        border-radius: 9px;
        overflow: hidden;

        .title {
          margin-right: 17px;
          // float: left;
          min-width: 60px;
          height: 30px;
          line-height: 30px;
          text-align: center;
          font-family: PMingLiU-ExtB;
          font-size: 14px;
          color: #ededed;
          background-color: #f6ad35;
          border-radius: 8px;
        }

        .content {
          cursor: default;
          min-height: unset;
          font-family: PMingLiU-ExtB;
          font-size: 14px;
          color: #000000;
        }

        .content:hover {
          background: unset;
        }
      }

      .scoreBox {
        margin-top: 10px;
      }
    }

    .isBrushComment {
      max-width: 395px;
    }
  }

  .answerRegion-active {
    height: unset;
    padding-bottom: 18px;
    overflow: unset;
  }

  .isBQuestion {
    display: block;
    padding-left: 3px !important;
  }

  .brushDialog {
  }
}

@media only screen and (max-width: 767px) {
  .taskType {
    .answerRegion {
      margin-top: 20px;
      padding-left: 0;

      .btn {
        position: absolute;
        bottom: 7px;
        left: 50%;
        transform: translate(-30%, 0);
      }
    }

    .el-dialog__body {
      iframe {
        width: 90vw;
        height: 80vh;
      }
    }
  }
}
</style>